﻿using System;
using System.Windows.Input;

namespace Mvvm
{
    /// <summary>
    /// Represents an object that relays commands.
    /// </summary>
    public class CommandRelay : ICommand
    {
        private Action<object> _commandDel;
        private Predicate<object> _commandCanExecuteDel;

        /// <summary>
        /// Raised when the call to CanExecute may return a value that is different from prior calls to CanExecute.
        /// </summary>
        public event EventHandler CanExecuteChanged;

        public CommandRelay(Action<object> command, Predicate<object> canExecutePred)
        {
            _commandDel = command;
            _commandCanExecuteDel = canExecutePred;
        }

        /// <summary>
        /// Returns true when the command can be executed. Returns false otherwise.
        /// </summary>
        public bool CanExecute(object parameter)
        {
            return _commandCanExecuteDel(parameter);
        }

        /// <summary>
        /// Executes the command with the given parameter.
        /// </summary>
        public void Execute(object parameter)
        {
            _commandDel(parameter);
        }

        /// <summary>
        /// Tells the RelayCommand that the next call to CanExecute may yield a result that is different from 
        /// calls to CanExecute that were made prior to calling this method.
        /// </summary>
        /// <param name="caller">
        /// A reference to the object that wishes to notify the CommandRelay.
        /// </param>
        public void ChangesMadeToCanExecute(object caller)
        {
            if (CanExecuteChanged != null)
                CanExecuteChanged(caller, new EventArgs());
        }
    }
}
